<?php
/**
 * Created by PhpStorm.
 * User: gqn
 * Date: 2016/3/14
 * Time: 19:37
 */

namespace Api\Controller;

Class OrderStatusController extends BaseController{

    /**
     * 判断订单是否存在
     */
    public function check($order_id){
        $data = M('repair_order')->where("repair_order_num_alias = $order_id")->find();
        if(!$data) {
            $info = array('err_code'=>'404','err_msg'=>'订单不存在！');
            $this->ajaxReturn($info);
        }

    }

    /**
     * 订单状态显示
     */
    public function index(){
        //解决跨域
        echoHeader();
        $order_id = I('post.order_id','');
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        self::check($order_id);
        $role = $data[user][identity];
        $short = M('repair_order')->field('repair_order_id')->where("repair_order_num_alias = $order_id")->find();
        $repair_order_id = $short['repair_order_id'];
        $sql = "select history.status,history.add_time,history.count,config.name,config.content,config.content1 from zsf_order_status_history as history left join zsf_config_status as config on history.status = config.status where history.order_id = $repair_order_id and history.order_type =1 and config.order_type = 1 and user_type = $role order by history.add_time asc";
        $model = M();
        $info = $model->query($sql);
        if(!empty($info)){
            foreach($info as $key=>$value){
                if($info[$key]['count'] !=0){
                    $info[$key]['content']  = $info[$key]['content1'];
                }
                if($info[$key]['status'] =='-1'){
                    $occ = M('repair_order')->field('user_id,worker_user_id')->where("repair_order_id = $repair_order_id")->find();
                    $cancel = M('repair_order_cancel')->where("order_id = $repair_order_id")->find();
                    if($cancel[user_id] == $occ['user_id']){
                        $info[$key]['content'] = '业主取消了该订单 理由是：'.$cancel['reason'].';'.$cancel['content'];
                    }
                    if($cancel[user_id] == $occ['worker_user_id']){
                        $info[$key]['content'] = '师傅取消了该订单 理由是：'.$cancel['reason'].';'.$cancel['content'];
                    }
                }
                $info[$key]['add_time'] = date('Y-m-d H:i:s', $info[$key]['add_time']);
            }
            $array = array("err_code" => 200, 'err_msg' => $info);
            $this->ajaxReturn($array);
        }else{
            $array = array("err_code" => 404, 'err_msg' => '暂无状态！');
            $this->ajaxReturn($array);
        }
    }

    /**
     * 订单状态按钮
     */
    public function  button(){
        //解决跨域
        echoHeader();
        $order_id = I('post.order_id','');
        /*1：抵达， 2:上门，3:立即开工,4:完工 5:验收通过 6:暂停维保金 7:取消暂停 8业主同意 9业主不同意 10业主申请退款 11师傅同意退款 12师傅拒绝退款 */
        $key = I('post.key','');
        if($order_id ==''|| $key ==''){
            $array = array("err_code"=>404,'err_msg'=>'参数缺失');
            $this->ajaxReturn($array);
        }
        self::check($order_id);
        $model = M();
        $sql = "SELECT repair.repair_order_id,repair.user_id,repair.worker_user_id,usr.phone as usrphone,wor.phone as worphone FROM zsf_repair_order as repair left join zsf_user as usr on usr.user_id = repair .user_id left join zsf_user as wor on repair.worker_user_id = wor.user_id WHERE ( repair.repair_order_num_alias = $order_id )";
        $id = $model->query($sql);
        $model ->startTrans();

        $repair_order_id = $id[0]['repair_order_id'];
        $worker_user_id = $id[0]['worker_user_id'];

        if($key=='1'){
            self::check_status($repair_order_id,$key);
            $status ='3';
        }
        if($key=='2'){
            self::check_status($repair_order_id,$key);
            $status ='-3';
        }
        if($key=='3'){
            self::check_status($repair_order_id,$key);
            $status ='5';
        }
        if($key=='4'){
            self::check_status($repair_order_id,$key);
            $status ='6';
        }
        if($key=='5'){
            self::check_status($repair_order_id,$key);
            $status ='7';
        }
        if($key=='6'){
            self::check_status($repair_order_id,$key);
            $status ='9';
        }
        if($key=='7'){
            self::check_status($repair_order_id,$key);
            $exist = M('UserRefund')->where("order_id = $repair_order_id")->find();
            if($exist){
                $array = array('err_code'=>403,'err_msg'=>'客服已处理退款！');
                $this->ajaxReturn($array);
            }
            $condition['count'] ='1';
            $status ='8';
        }
        if($key=='8'){
            $keys = 10;
            self::check_status($repair_order_id,$keys);
            $confirm = self::confirm_update('1',$order_id);

            $status = '-2';
            $keys = array(1,2,3,4);
            if(in_array($key,$keys)){
                $role = 2;
            }else{
                $role = 1;
            }
            $return = $this->getRepairStatus($status,$repair_order_id,$role,$confirm['err_msg']);
            $this->agreeChange($order_id,$worker_user_id);
            $array = array("err_code"=>200,'err_msg'=>$return);
            $this->ajaxReturn($array);

        }
        if($key=='9'){
            $keys = 10;
            self::check_status($repair_order_id,$keys);
            $this->agreeChange($order_id,$worker_user_id);
            $confirm = self::confirm_update('2',$order_id);

            $status = '3';
            $keys = array(1,2,3,4,8);
            if(in_array($key,$keys)){
                $role = 2;
            }else{
                $role = 1;
            }
            $return = $this->getRepairStatus($status,$repair_order_id,$role,$confirm['err_msg']);
            $array = array("err_code"=>200,'err_msg'=>$return);
            $this->ajaxReturn($array);
        }

        if($key=='10'){
            $user_id = I('post.user_id');//用户id
            $channel = I('post.channel');//退款渠道
            $bank_name = I('post.bank_name','');
            $account_name = I('post.account_name');
            $account_num = I('post.account_num');
            $money = I('post.money'); //退款金额
            $desc = I('post.desc');//退款说明
            $type = I('post.type','0'); //0全部1维保金

            //看申请是否存在
            $refundExist = M('repair_order_refund')->where("order_id = $repair_order_id")->find();
            if($refundExist){
                $array = array('err_code'=>403,'err_msg'=>'该订单已申请过退款');
                $this->ajaxReturn($array);
            }

            //退款申请表增加记录
            $refund['order_id'] = $repair_order_id;
            $refund['user_id'] = $user_id;
            $refund['channel'] = $channel;
            $refund['bank_name'] = $bank_name;
            $refund['account_name'] = $account_name;
            $refund['account_num'] = $account_num;
            $refund['money'] = $money;
            $refund['desc'] = $desc;
            $refund['type'] = $type;
            $refund['add_time'] = time();
            M('repair_order_refund')->add($refund);
            if($type==1) {
                $status = '11';
            }else{
                $status = '12';
            }
        }

//        if($key=='11'){
//            $status = '12';
//        }
//        if($key=='12'){
//            $status = '13';
//        }

        $repair['repair_order_id'] = $repair_order_id;
        $repair['status'] = $status;
        M('repair_order')->save($repair);

        $condition['order_type'] = '1';
        $condition['order_id'] = $repair_order_id;
        $condition['add_time'] = time();
        $condition['status'] = $status;
        $end = M('order_status_history')->add($condition);

        if($end){
            $model->commit();
            $keys = array(1,2,3,4);
            if(in_array($key,$keys)){
                $role = 2;
            }else{
                $role = 1;
            }
            $return = $this->getRepairStatus($status,$repair_order_id,$role,$end);
            $array = array("err_code"=>200,'err_msg'=>$return);
            $this->ajaxReturn($array);
        }else {
            $model->rollback();
            $array = array("err_code" => 403, 'err_msg' => '提交失败！');
            $this->ajaxReturn($array);
        }

    }

    /**
     * 取消订单
     */

    public function cancel(){
        //解决跨域
        echoHeader();
        $order_id = I('post.order_id','');
        self::check($order_id);
        $id = M('repair_order')->field('repair_order_id,status')->where("repair_order_num_alias = $order_id")->find();

        $repair_order_id = $id[repair_order_id];
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $key = '8';
        self::check_status($repair_order_id,$key);

        $model = M();
        $model ->startTrans();

        $repair['repair_order_id'] = $repair_order_id;
        $repair['status'] = '-1';
        $order_Save = M('repair_order')->save($repair);

        $info['order_id'] = $repair_order_id;
        $info['reason'] = trim(I('post.reason','')); //取消原因
        $info['content'] = trim(I('post.content',''));//取消内容
        $info['user_id'] = $user_id;
        $info['add_time'] = time();
        $order_Cancel = M('repair_order_cancel')->add($info);

        $status['order_type'] = 1;
        $status['order_id'] = $repair_order_id;
        $status['add_time'] = time();
        $status['status'] = '-1';
        $order_status = M('order_status_history')->add($status);

        if($order_Cancel && $order_Save && $order_status){
            S(C('REPAIR_ORDER') . '_key_' . $order_id,2,60);
            $pushwhere['order_id'] = $repair_order_id;
            $pushsave['status'] = '2';
            M('pushorder')->where($pushwhere)->save($pushsave);
            $model->commit();
            $array = array("err_code"=>200,'err_msg'=>'提交成功！');
            $this->ajaxReturn($array);
        }else{
            $model->rollback();
            $array = array("err_code" => 403, 'err_msg' => '提交失败！');
            $this->ajaxReturn($array);
        }
    }




    public function checkcomment(){
        //解决跨域
        echoHeader();
        $order_id = I('post.order_id','');
        self::check($order_id);
        $id = M('repair_order')->field('repair_order_id')->where("repair_order_num_alias = $order_id")->find();
        $repair_order_id = $id[repair_order_id];
        $key = '9';
        self::check_status($repair_order_id,$key);

        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $role = $data[user][identity];
        $order_id = I('post.order_id');
        self::check($order_id);
        $type = I('post.type','');
        if($type==''){
            $array = array("err_code"=>403,'err_msg'=>'参数缺失');
            $this->ajaxReturn($array);
        }
        if($role =='1') {
            $data = M('comment')->field('speed,attitude,skill,content,append_content')->where("user_id = $user_id and order_id = $order_id and type = $type")->find();
        }else{
            $data = M('comment')->field('speed,attitude,skill,content,append_content')->where("worker_user_id = $user_id and order_id = $order_id and type = $type")->find();
        }
        if($data) {
            $array = array("err_code" => 200, 'err_msg' => $data);
            $this->ajaxReturn($array);
        }else{
            $array = array("err_code" => 404, 'err_msg' =>'找不到评价');
            $this->ajaxReturn($array);
        }
    }  

    public function check_status($repair_order_id,$key){
        //解决跨域
        echoHeader();
        $data = M('repair_order')->field('status')->where("repair_order_id = $repair_order_id ")->find();
        if($key == '1'){
            if($data['status']!='-3'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '2'){
            if($data['status']!='2'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '3'){
            if($data['status']!='-2'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '4'){
            if($data['status']!='5'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '5'){
            if($data['status']!='6'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '6'){
            if($data['status']!='8'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '7'){
            if($data['status']!='9'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '8'){
            if($data['status']=='10'|| $data['status']=='-1'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '9'){
            if($data['status']!='8' || $data['status']!='9' || $data['status']!='10'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }
        if($key == '10'){
            if($data['status']!='4'){
                $info = array('err_code'=>403,'err_msg'=>'订单状态出错');
                $this->ajaxReturn($info);
            }elseif($data['status']=='-1'){
                $info = array('err_code'=>404,'err_msg'=>'该订单已取消');
                $this->ajaxReturn($info);
            }
        }

    }

    /**
     * 取消原因/投诉原因
     * @param user_id 用户id
     * @param status 1维修2装修
     */
    public function GetReason()
    {
        //解决跨域
        echoHeader();
        $type = I('post.type'); //1取消 2投诉
        $status = I('post.status'); //1维修
        if($type =='1') {
            $user_id = I('post.user_id');
            $data = self::checkUserIsExist($user_id);
            if (!$data['user']) {
                $this->ajaxReturn($data);
            }
            $role = $data[user][identity];
            $info = M('config_cancel')->field('reason')->where("role = $role and status = $status and type = $type")->select();
        }else{
            $info = M('config_cancel')->field('reason')->where("status = $status and type = $type")->select();
        }
        if ($info) {
            $end = array('err_code' => 200, 'err_msg' => $info);
            $this->ajaxReturn($end);
        }else{
            $end = array('err_code'=> 403,'err_msg'=>'暂无配置');
            $this->ajaxReturn($end);
        }
    }


    /**
     * 未完成未支付订单
     * @param user_id 用户id
     * @param status 1弹窗 2列表
     * @业主 未支付未评价  师傅 暂停维保待未评价
     */
    public function unfinished(){
        //解决跨域
        echoHeader();
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if (!$data['user']) {
            $this->ajaxReturn($data);
        }
        $role = $data[user][identity];
        //1未支付未完成窗口 2待支付待评价列表
        $status = I('post.status');

        if($status!=1) {
            if($role == 1){
                //未支付订单
                $unp = M('repair_order')->field('repair_order_num_alias')->where("status = 7 and user_id = $user_id")->select();
                //未评价订单
                //当前时间小于三天后的支付时间
                $unc = M('repair_order')->field('repair_order_num_alias,pay_time')->where("status between 7 and 10 and user_id = $user_id and user_comment = 0")->select();
                foreach($unc as $k=>$v){
                    $oldtime = strtotime('3 day',$v['pay_time']);
                    if(time() > $oldtime){
                        unset($unc[$k]);
                    }
                }
                //业主端 未评价 未支付订单
                if($unp) {
                    $unp = array_column($unp, 'repair_order_num_alias');
                    $RepairOrder = $unp;
                }
                if($unc) {
                    $unc = array_column($unc, 'repair_order_num_alias');
                    $RepairOrder = $unc;
                }
                if($unp && $unc){
                    $RepairOrder = array_merge($unp,$unc);
                }
                if($RepairOrder){
                    $order_id = implode(',',$RepairOrder);
                }else{
                    $array = array('err_code'=>403,'err_msg'=>'暂无订单');
                    $this->ajaxReturn($array);
                }

            }elseif($role == 2){
                //师傅段 暂停维保 未评价订单
                $masterStop = M('repair_order')->field('repair_order_num_alias')->where("status = 9 and worker_user_id = $user_id")->select();

                $masterUnc = M('repair_order')->field('repair_order_num_alias,pay_time')->where("status = 8 and worker_user_id = $user_id and master_comment = 0")->select();
                foreach($masterUnc as $k=>$v){
                    $oldtime = strtotime('3 day',$v['pay_time']);
                    if(time() > $oldtime){
                        unset($masterUnc[$k]);
                    }
                }

                if($masterStop){
                    $stop = array_column($masterStop, 'repair_order_num_alias');
                    $RepairOrder = $stop;
                }
                if($masterUnc) {
                    $unc = array_column($masterUnc, 'repair_order_num_alias');
                    $RepairOrder = $unc;
                }
                if($masterStop && $masterUnc){
                    $RepairOrder = array_merge($stop,$unc);
                }
                if($RepairOrder){
                    $order_id = implode(',',$RepairOrder);
                }else{
                    $array = array('err_code'=>403,'err_msg'=>'暂无订单');
                    $this->ajaxReturn($array);
                }


            }

            $data = M()->table('zsf_repair_order rep')->field("rep.user_comment,rep.master_comment,rep.repair_order_id,rep.user_id,rep.fixed_price,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,usr.lat as usrlat,usr.lng as usrlng,wor.lat as worlat,wor.lng as worlng,rep.lat as addr_lat,rep.lng as addr_lng")
                    ->join("LEFT JOIN zsf_user usr on usr.user_id = rep.user_id")
                    ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                    ->where("rep.repair_order_num_alias in($order_id) and rep.status !=-1")
                    ->order('rep.repair_order_id desc')
                    ->select();

            if($data){
                foreach($data as $k=>$v){
                    //业主待支付
                    if($v['status']==7 && $role ==1){
                        $data[$k]['execute'] =  1;
                    }
                    //业主待评价
                    if($v['status']>7 && $v['user_comment']==0 && $role ==1){
                        $data[$k]['execute'] =  2;
                    }
                    //业主暂停了
                    if($v['status']==9 && $v['master_comment']==1 && $role==2){
                        $data[$k]['execute'] = 3;
                    }
                    //师傅待评价
                    if($v['status']==8 && $v['master_comment']==0 && $role==2){
                        $data[$k]['execute'] = 4;
                    }

                    $data[$k]['order_time'] = date('m-d H:i', $data[$k]['order_time']);
                    $data[$k]['set_time'] = date('m-d H:i', $data[$k]['set_time']);
                    //换地址
                    if($data[$k]['worker_user_id']!=0) {
                        $distance = getDistance($data[$k]['addr_lat'], $data[$k]['addr_lng'], $data[$k]['worker_lat'], $data[$k]['worker_lng']);
                    }else{
                        $distance = '-1';
                    }
                    $data[$k]['distance'] = $distance;
                    if($data[$k]['book_time']!='0'){
                        $data[$k]['book_time'] = date('m-d H:i', $data[$k]['book_time']);
                    }
                    $map['fault_id'] = array('in',$data[$k]['fault_id_list']);
                    $info = M('fault')->field('name')->where($map)->select();
                    $names = array_column($info, 'name');
                    $data[$k]['fault_name'] = implode(';',$names);

                    $sql = "select config.name from zsf_order_status_history as history left join zsf_config_status as config on history.status = config.status where history.order_id = ". $data[$k]['repair_order_id']." and history.order_type = 1 and config.order_type = 1 and user_type = $role  order by history.add_time desc limit 1";
                    $end = M()->query($sql);
                    $data[$k]['action'] = $end[0]['name'];
                }
                $array = array('err_code'=>200,'err_msg'=>$data);
                $this->ajaxReturn($array);

            }
        }

    }

    /**
     * 无人抢订单
     * @param user_id 用户id
     * @param mode 模式
     * @param condition 筛选
     */
    public function getOrder(){
        //解决跨域
        echoHeader();
        $user_id = I('post.user_id');
        $usr = self::checkUserIsExist($user_id);
        if (!$usr['user']) {
            $this->ajaxReturn($usr);
        }
        $mode_charging = I('post.mode'); //1顺风 2标准 3专修
        if(!$mode_charging){
            $ext = array('err_code'=>404,'err_msg'=>'参数缺失');
            $this->ajaxReturn($ext);
        }
        $condition = I('post.condition','1'); //1距离 2时间 3价格
        $page = I('post.page','1'); //页码;
        $size = I('post.size','10'); //每页显示数
        $info = M()->table('zsf_user_repair_conf conf')->field('category.category_name')->join('zsf_category category on conf.category_id = category.category_id')->where("conf.user_id = $user_id")->select();
        if(!$info){
            $ext = array('err_code'=>202,'err_msg'=>'请先设置维修技能！');
            $this->ajaxReturn($ext);
        }
        $names = array_column($info, 'category_name');
        $name = '';
        foreach($names as $y => $j){
            $name .='\''.$names[$y].'\''.',';
        }
        $name = substr($name,0,strlen($name)-1);
        if($condition =='1'){
            $count ="SELECT count(*) FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.user_id != $user_id AND rep.mode_charging = $mode_charging";
            $counts = M()->query($count);
            $limit =($page-1)*$size;
            $pages = ceil($counts[0]['count(*)']/$size);
            $sql ="SELECT rep.repair_order_id,rep.fixed_price,rep.user_id,rep.doorplate,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worlat,wor.lng as worlng,round(6378.138*2*asin(sqrt(pow(sin((rep.lat*pi()/180-wor.lat*pi()/180)/2),2)+cos(rep.lat*pi()/180)*cos(wor.lat*pi()/180)* pow(sin( (rep.lng*pi()/180-wor.lng*pi()/180)/2),2)))*1000) as distance FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.user_id != $user_id AND  rep.mode_charging = $mode_charging  ORDER BY distance asc limit ".$limit.','.$size;
        }elseif($condition =='2'){
            $count = "SELECT count(*) FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.mode_charging = $mode_charging";
            $counts = M()->query($count);
            $limit =($page-1)*$size;
            $pages = ceil($counts[0]['count(*)']/$size);
            $sql = "SELECT rep.repair_order_id,rep.fixed_price,rep.user_id,rep.doorplate,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worlat,wor.lng as worlng FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.user_id != $user_id AND  rep.mode_charging = $mode_charging ORDER BY set_time desc limit ".$limit.','.$size;
        }elseif($condition =='3'){
            $count = "SELECT count(*) FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.mode_charging = $mode_charging";
            $counts = M()->query($count);
            $limit =($page-1)*$size;
            $pages = ceil($counts[0]['count(*)']/$size);
            $sql = "SELECT rep.repair_order_id,rep.fixed_price,rep.user_id,rep.doorplate,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worlat,wor.lng as worlng FROM zsf_repair_order rep INNER JOIN zsf_user usr on usr.user_id = rep.user_id INNER JOIN zsf_user wor on wor.user_id = $user_id WHERE rep.category_name IN ($name) AND rep.worker_user_id = 0 AND rep.status = 1 AND rep.user_id != $user_id AND  rep.mode_charging = $mode_charging ORDER BY total desc limit ".$limit.','.$size;
        }
        $data = M()->query($sql);
        if($data){
            foreach($data as $k=>$v){
                $data[$k]['order_time'] = date('m-d H:i', $data[$k]['order_time']);
                $data[$k]['set_time'] = date('m-d H:i', $data[$k]['set_time']);
                $distance = getDistance($data[$k][addr_lat],$data[$k][addr_lng],$data[$k][worlat],$data[$k][worlng]);
                $data[$k]['distance'] = $distance;
                if($data[$k]['book_time']!='0'){
                    $data[$k]['book_time'] = date('m-d H:i', $data[$k]['book_time']);
                }
                $map['fault_id'] = array('in',$data[$k]['fault_id_list']);
                $info = M('fault')->field('name')->where($map)->select();
                $name = array_column($info,'name');
                $data[$k]['fault_name'] = implode(',',$name);
            }
            $ext = array('err_code'=>200,'err_msg'=>$data,'pages'=>$pages);
            $this->ajaxReturn($ext);
        }else{
            $ext = array('err_code'=>203,'err_msg'=>'暂时没有订单');
            $this->ajaxReturn($ext);
        }

    }

    /**
     * 删除订单
     */
    public function delOrder(){
        $user_id = I('post.user_id');
        $order_id = I('post.repair_order_num_alias');
        $usr = self::checkUserIsExist($user_id);
        if (!$usr['user']) {
            $this->ajaxReturn($usr);
        }
        $map['user_id'] = $user_id;
        $map['repair_order_num_alias'] = $order_id;
        $data = M('repair_order')->field('status')->where($map)->find();
        if($data['status']!='10'){
            $array = array('err_code'=>404,'err_msg'=>'该订单不能删除！');
            $this->ajaxReturn($array);
        }
        $map['status'] = 0;
        $info = M('repair_order')->save($map);
        if($info){
            $array = array('err_code'=>200,'err_msg'=>'删除成功！');
            $this->ajaxReturn($array);
        }else{
            $array = array('err_code'=>203,'err_msg'=>'删除失败！');
            $this->ajaxReturn($array);
        }

    }

    /**
     * 获取订单状态
     */

    public function getRepairStatus($status,$order_id,$role,$end){
        $return['status'] = $status;
        $data = M()->table('zsf_order_status_history his')->field('his.add_time,his.count,sta.name,sta.content,sta.content1')->join("LEFT JOIN zsf_config_status sta on his.status = sta.status and sta.user_type = $role")->where("his.id = $end")->select();
        if($data[0]['count']!=0){
            $data[0]['content'] = $data[0]['content1'];
        }
        $data[0]['add_time'] = date('Y-m-d H:i:s',$data[0]['add_time']);
        $return['order_status'] = $data[0]['content'];
        $return['order_status_name'] = $data[0]['name'];
        $return['order_status_time'] = $data[0]['add_time'];
        if($status =='1' || $status =='2' || $status =='-3'){
            $return['order_status_type'] = '待服务';
        }
        if($status =='-2' || $status =='3' || $status =='4'|| $status =='5'|| $status =='6' || $status =='7'){
            $return['order_status_type'] = '服务中';
        }
        if($status =='8' || $status =='9'){
            $return['order_status_type'] = '维保中';
        }
        if($status =='-1' || $status =='10'){
            $return['order_status_type'] = '已完成';
        }
        $inf = M()->table('zsf_repair_order rep')->field('rep.user_id,rep.worker_user_id,usr.lat as usrlat,usr.lng as usrlng,wok.lat as woklat,wok.lng as woklng')->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")->join("LEFT JOIN zsf_user wok on rep.worker_user_id = wok.user_id")->where("rep.repair_order_id = $order_id")->select();
        $distane = getDistance($inf[0]['usrlat'], $inf[0]['usrlng'], $inf[0]['woklat'], $inf[0]['woklng']);
        $return['distance'] = $distane;

        return $return;

    }


    /**
     * 订单确认修改
     */
    public function confirm_update($flag,$order_id)
    {

        $return = array();
        $flag = $flag == 1 ? 1 : 0;
        $total = 0;//总价
        $detailIds = array();//故障列表

//        $phone = I('post.phone', '', '/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/');//用户名
//        $key = I('post.key', '', 'special_chars');//key
//        $rid = I('post.rid/d', '');//当前登录用户的登录角色
//        $order_id = I('post.order_id', '');//订单对外id
//        $flag = (int)I('post.flag', '');//为1则是同意，否则是不同意
//        $checkInfo = checkRole($phone, $key, $rid, false);//检测当前登录用户是否有操作权限
//        if ($checkInfo['code'] != 200) {
//            $this->ajaxReturn($checkInfo, 'JSON');
//        }
//        $user = M('user');
//        $userMap['phone'] = $phone;
//        $userInfo = $user->field('user_id')->where($userMap)->find();

        $RepairOrder = M('RepairOrder');
        $orderMap = array();
        $orderMap['repair_order_num_alias'] = $order_id;
        $orderInfo = $RepairOrder->where($orderMap)->find();

//        if ($orderInfo['user_id'] != $userInfo['user_id']) {//订单只能允许该笔订单的创建者去操作
//            $return['code'] = 2010;
//            $return['msg'] = '您不是该订单的业主';
//            $this->ajaxReturn($return, 'JSON');
//        }

        $RepairOrderDetail = M('RepairOrderDetail');
        $orderDetailMap = array();
        $orderDetailMap['repair_order_id'] = $orderInfo['repair_order_id'];
        $orderDetailMap['status'] = 1;
        $detaiInfo = $RepairOrderDetail->where($orderDetailMap)->select();
        $RepairOrderProtocol = M("RepairOrderProtocol");
        $repairInfo = $RepairOrderProtocol->where(array('status' => 1, 'order_id' => $order_id))->find();

        if (!empty($detaiInfo) || !empty($repairInfo)) {
            $RepairOrder->startTrans();
            if ($flag == 1) {
//                业主同意情况下的处理,查找该笔订单的背修改的记录
                if (!empty($detaiInfo)) {
                    $fault_id_list = array();
                    foreach ($detaiInfo as $key => $val) {
                        $total = bcadd($total, $val['price'], 2);//计算总钱
                        $fault_id_list[] = $val['fault_id'];
                        $detailIds[] = $val['id'];
                    }
                    $total = bcadd($total, $orderInfo['diagnosis_cost'], 2);//计算总钱
                    $fault_id_list_str = implode(',', $fault_id_list);
                    $orderData = array();
                    $orderData['fault_id_list'] = $fault_id_list_str;
                    $orderData['total'] = $total;
                }

                $orderData['protocol_id'] = $repairInfo['protocol_id'];
                $orderData['status'] = -2; //开始服务了
                $res = $RepairOrder->where($orderMap)->save($orderData);

                //同意情况下降状态为1[师傅修改]的修改成2[业主同意]
                $repairInfoStatus0Info = $RepairOrderDetail->where(array('status' => 1, 'repair_order_id' => $orderInfo['repair_order_id']))->find();
                if (!empty($repairInfoStatus0Info)) {
                    $status0 = $RepairOrderDetail->where(array('status' => 1, 'repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 2));//修改订单状态为1的修改成2
                } else {
                    //如果不存在订单状态为1的情况下，将状态为0的修改成2[业主同意]
                    $status0 = $RepairOrderDetail->where(array('status' => 0, 'repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 2));//修改订单状态为0的修改成2
                }

                //师傅诊断后，业主同意后 将[协议表]状态为[师傅修改]1的支付协议，修改成[业主同意]2
                $repairInfoStatus1Info = $RepairOrderProtocol->where(array('status' => 1, 'order_id' => $order_id))->find();
                if (!empty($repairInfoStatus1Info)) {
                    //修改订单状态为1的修改成2
                    $status4 = $RepairOrderProtocol->where(array('status' => 1, 'order_id' => $order_id))->save(array('status' => 2));
                } else {
                    //找不到状态为1的情况下，将状态为0的修改成2
                    $status4 = $RepairOrderProtocol->where(array('status' => 0, 'order_id' => $order_id))->save(array('status' => 2));
                }

                //同意情况下，将协议表 状态为3[业主不同意]的修改成[废弃状态]4
                $repairInfoStatus3Info = $RepairOrderProtocol->where(array('status' => 3, 'order_id' => $order_id))->find();
                if (!empty($repairInfoStatus3Info)) {
                    $status5 = $RepairOrderDetail->where(array('status' => 3, 'repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 4));
                } else {
                    $status5 = 1;
                }

                if ($res > 0 && $status0 > 0 && $status4 > 0 && $status5 > 0) {
                    //增加订单状态到历史状态表
                    $end = $this->addToHistory($orderInfo['repair_order_id'], -2, 0);

                    //将状态为2的订单详细价格加起来
                    $price = M('RepairOrderDetail')->where(array("status" => 2, "repair_order_id" => $orderInfo['repair_order_id']))->field('price,fault_id')->select();
                    $pri = '';
                    $fault_id_list = '';
                    foreach ($price as $k => $v) {
                        $pri = bcadd($pri, $v['price'], 2);
                        $fault_id_list .= $v['fault_id'].',';
                    }
                    $fault_id_list =substr($fault_id_list,0,-1);
                    $pri = bcadd($pri, $orderInfo['diagnosis_cost'], 2);

                    //一口价
                    $order_protocol = $RepairOrderProtocol->field('fixed_price')->where(array('status' => 2, 'order_id' => $order_id))->order('donetime desc')->find();
                    if(!empty($order_protocol)){
                        $reOrder['fixed_price'] = $order_protocol['fixed_price'];
                    }
                    $reOrder['total'] = $pri;

                    //更新故障ID
                    $reOrder['fault_id_list'] = $fault_id_list;
                    $reOrder['fault_type'] = 1;
                    M('RepairOrder')->where(array('repair_order_id' => $orderInfo['repair_order_id']))->save($reOrder);

                    $RepairOrder->commit();//修改成功
                    $return['err_code'] = 200;
                    $return['err_msg'] = $end;
                } else {
                    $return['err_code'] = 2014; //修改失败
                    $return['err_msg'] = '修改失败，未知错误';
                    $RepairOrder->rollback();
                }
                //修改订单表中的fault_id_list,//修改订单表中的total,//修改订单表中的status

            } else {
                //业主不同意情况下的处理
                //将状态改成3//为业主不同意
                $orderDetail = $RepairOrderDetail->where(array('status' => 1, 'repair_order_id' => $orderInfo['repair_order_id']))->find();
                if (!empty($orderDetail)) {
                    $res = $RepairOrderDetail->where(array('status' => 1, 'repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 3));//修改订单状态为0的修改成2
                } else {
                    $res = 1;
                }

                $orderProtocolInfo = $RepairOrderProtocol->where(array('status' => 1, 'order_id' => $order_id))->find();
                if (!empty($orderProtocolInfo)) {
                    $res2 = $RepairOrderProtocol->where(array('status' => 1, 'order_id' => $order_id))->save(array('status' => 3));//修改订单状态为0的修改成2
                } else {
                    $res2 = 1;
                }
                $repairOrderInfo = $RepairOrder->where(array('status' => 3, 'repair_order_id' => $orderInfo['repair_order_id']))->find();
                if (empty($repairOrderInfo)) {
                    $res3 = $RepairOrder->where(array('repair_order_id' => $orderInfo['repair_order_id']))->save(array('status' => 3));
                } else {
                    $res3 = 1;
                }
                if ($res > 0 && $res2 > 0 && $res3 > 0) {
                    $end = $this->addToHistory($orderInfo['repair_order_id'], 3, 1);
                    $return['err_code'] = 200;
                    $return['err_msg'] = $end;
                    $RepairOrder->commit();//修改成功u
                } else {
                    $return['err_code'] = 2014;
                    $return['err_msg'] = '修改失败，未知错误';
                    $RepairOrder->rollback();
                }
            }
        } else {
            $return['err_code'] = 2015;
            $return['err_msg'] = '修改失败，查询不到修改记录';
        }
        return $return;
        //只能是该业主去确认，获取是取消、
        //如果确认了之后，则取修改订单表对应的字段
        //[确认了就将状态设置为-2][取消则将状态设置为3]
        //而且还要修改订单详情表的记录
        //还要修改历史记录表
    }

    /**
     * 增加订单状态
     */

    private function addToHistory($result, $status, $count = 0)
    {
        $OrderStatusHistory = M('OrderStatusHistory');
        $historyData = array();
        $historyData['order_id'] = $result;
        $historyData['status'] = $status;
        $historyData['order_type'] = 1;
        $historyData['add_time'] = time();
        $historyData['count'] = $count;
        $res = $OrderStatusHistory->add($historyData);
        return $res;
    }

    /**
     * 查询订单是否被取消
     */
    private function orderisCancel($order_id){
        $order=M('repair_order')->where("repair_order_id = $order_id")->find();
        if($order['status']==-1){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 师傅轮询修改订单是否同意
     */
    public function agreeChange($order_id,$master_id){
        if(empty($order_id)){
            $data=array(err_code=>1003,err_msg=>'缺少订单id');
            return $data;
        }
        if(empty($master_id)){
            $data=array(err_code=>1003,err_msg=>'缺少用户id');
            return $data;
        }

        //查询订单是否存在
        $oWhere['repair_order_num_alias']=$order_id;
        $oWhere['worker_user_id']=$master_id;
        $order = M('repair_order')->where($oWhere)->limit(1)->select();
        if(empty($order)){
            $data = array(err_code=>1004,err_msg=>'订单不存在');
            return $data;
        }

        $isCancel=$this->orderisCancel($order[0]['repair_order_id']);
        if(!$isCancel){
            $data=array(err_code=>1234,err_msg=>'订单已取消');
            return $data;
        }

        $dWhere['repair_order_id']=$order[0]['repair_order_id'];
        $dflag=0;
        $pflag=0;
        $dorder = M('repair_order_detail')->where($dWhere)->select();

        if(empty($dorder)) {
            $data = array(err_code => 1101, err_msg => '故障不存在');
            return $data;
        }
        foreach($dorder as $d=>$dv){
            switch($dv['status']){
                case 2:
                    $dflag=2;
                    break;break;
                case 0:
                    $dflag=2;
                    break;break;
                case 3:
                    $dflag=3;
                    $dWhere['status']=3;
                    $mapDe['status']=4;
                    $dorder = M('repair_order_detail')->where($dWhere)->save($mapDe);
                    break;break;
            }
        }

        $pWhere['order_id']= $order_id;
        $porder=M('repair_order_protocol')->where($pWhere)->select();
        foreach($porder as $p=>$pv){
            switch($pv['status']){
                case 2:
                    $pflag=2;
                    break;break;
                case 3:
                    $pflag=3;
                    $pWhere['status']=3;
                    $mapPro['status']=4;
                    M('repair_order_protocol')->where($pWhere)->save($mapPro);
                    break;break;
            }
        }

        //业主同意
        if($dflag==2 && $pflag==2){
            //修改订单状态  0变4 2变0
            $detail=M('repair_order_detail');
            $detail->startTrans();
            $dcWhere['repair_order_id']=$order[0]['repair_order_id'];

            $change0_4 =true;
            $change2_0 =true;
            $changep0_4 =true;
            $changgep2_0 =true;

//            $changDetail=$detail->where($dcWhere)->find();
//            if(!empty($changDetail)){
//                //把旧有的订单故障状态改为丢弃的
//                $changeD['status']=4;
//                $change0_4=$detail->where($dcWhere)->save($changeD);
//            }

            //把新修改的订单故障修改为正常状态的
            $dcWhere['status']=2;
            $change2 = $detail->where($dcWhere)->select();

            if(!empty($change2)){
                $changeD['status']=0;
                $change2_0=$detail->where($dcWhere)->save($changeD);
            }

            //修改订单支付协议状态 0变4 2变0
            $pcWhere['order_id']= $order_id;
            $pcWhere['status']=0;
            $changeP['status']=4;
            $changep = M('repair_order_protocol')->where($pcWhere)->select();

            if(!empty($changep)){
                $changep0_4 = M('repair_order_protocol')->where($pcWhere)->save($changeP);
            }
            $pcWhere['status']=2;
            $changeP['status']=0;
            $changgep2 = M('repair_order_protocol')->where($pcWhere)->select();

            if(!empty($changgep2)){
                $changgep2_0=M('repair_order_protocol')->where($pcWhere)->save($changeP);
            }

            if($change0_4 && $change2_0 && $changep0_4 && $changgep2_0){
                $detail->commit();
            }else{
                $detail->rollback();
                $data = array(err_code=>1113,err_msg=>'发生回滚错误');
                return $data;
            }

            //更新订单总金额
            $sum=M('repair_order_detail')->where("status = 0 and repair_order_id=".$order[0]['repair_order_id'])->field('sum(price) sum')->find();
            $fixed_price = M('repair_order_protocol')->where("status = 0 and order_id = $order_id")->field('fixed_price')->find();
            if(!empty($fixed_price)){
                $data['fixed_price'] = $fixed_price['fixed_price'];
            }
            $data['fault_money']=$sum['sum'];
            M('repair_order')->where("repair_order_id=".$order[0]['repair_order_id'])->save($data);

//            if($order[0]['volume_list_id']){
//                $volume=M('zsf_volume_list')->where("volume_list_id=".$order[0]['volume_list_id'])->field('total')->find();
//                $sum=bcsub($sum['sum'],$volume['total']);
//            }

            $sql="update zsf_repair_order set total=diagnosis_cost+".$sum['sum']." where repair_order_id=".$order[0]['repair_order_id'];
            M()->execute($sql);

            $data = array(err_code=>200,err_msg=>'同意');
            return $data;

        }elseif($dflag==3 || $pflag==3){
            $data = array(err_code=>1006,err_msg=>'不同意');
            return $data;
        }else{
            $data = array(err_code=>1007,err_msg=>'other');
            return $data;
        }
    }


    /**
     * 查询最近使用的退款账号
     */

    public function usedAccount(){
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $data = array();
        $info = M('RepairOrderRefund')->Where("user_id = $user_id")->order('add_time desc')->find();
        if($info){
            $data = $info;
        }
        $array = array('err_code'=>200,'err_msg'=>$data);
        $this->ajaxReturn($array);
    }

}